package com.zhuangwei.service;

import com.zhuangwei.dao.UserDao;
import com.zhuangwei.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * @author LeviCoder
 * @create 2019-03-09 23:18
 */
@SuppressWarnings("Duplicates")
@Service
public class UserConsumerService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private DiscoveryClient discoveryClient;
    @Autowired
    private RestTemplate restTemplate;

    public List<User> queryUserByIds(List<Long> ids) {
        List<User> users = new ArrayList<>();
        for (Long id : ids) {
            User user = this.userDao.queryUserById(id);
            users.add(user);
        }
        return users;
    }

    public List<User> findByIds(List<Long> ids) {
        List<User> users = new ArrayList<>();
        //根据服务名称，获取服务实例
        List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
        //因为只有一个user-service实例，所以直接get(0)
        ServiceInstance instance = instances.get(0);
        // 获取ip和端口号信息
        String baseUrl = "http://" +instance.getHost()+":"+ instance.getPort()+"/user";
        ids.forEach(id -> {
            // 这里我们多次请求数据库查询
            users.add(this.restTemplate.getForObject(baseUrl + id, User.class));
            // 每次间隔500毫秒
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        return users;
    }
    public List<User> findByIds2Ribbon(List<Long> ids) {
        List<User> users = new ArrayList<>();
        // 地址直接写服务名称即可
        String baseUrl = "http://user-service/user/";
        ids.forEach(id -> {
            // 这里我们多次请求数据库查询
            users.add(this.restTemplate.getForObject(baseUrl + id, User.class));
            // 每次间隔500毫秒
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        return users;
    }

}
